import { ElNotification } from 'element-plus'
import WangEditor from 'wangeditor'

import $http from '@/api/http'
import { useUser } from '@/store/user'

const imgSize = 5
// hack alert 修改为wangEditor专属属性
window.alert = function () {
  ElNotification({
    title: '图片上传失败',
    message: `图片大小不能超过${imgSize}MB`,
    type: 'error',
  })
}
export default class Edite {
  // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
  constructor({ wrap = '#blog-editor--wrap' } = {}) {
    this.wrap = wrap
    this.user = {}
    this.init()
    this.option()
    this.upload()
    this.editor.create()
    // 在组建中调用, 就可以使用user了, 这时候store已经挂载
    this.user = useUser()
    // eslint-disable-next-line no-constructor-return
    return this.editor
  }
  // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
  init() {
    this.editor = new WangEditor(this.wrap)
  }
  // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
  option() {
    this.editor.config.zIndex = 1
    this.editor.config.uploadImgMaxSize = imgSize * 1024 * 1024 // 5M
    this.editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
    this.editor.config.uploadImgMaxLength = 3
    this.editor.config.uploadFileName = 'file'
    this.editor.config.uploadImgHeaders = {
      Authorization: `Bearer ${this.user?.token}`,
    }
  }
  // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
  upload() {
    this.editor.config.customUploadImg = async function (resultFiles, insertImgFn) {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      let form = new FormData()
      for (let i = 0, len = resultFiles.length; i < len; i++) {
        await form.append('file', resultFiles[i])
      }
      try {
        let result = await $http({ type: 'uploadArticle', data: form })
        result.data.forEach(async (item) => {
          await insertImgFn(item.fileUrl)
        })
      } catch (err) {
        console.log(err)
        ElNotification({
          title: '错误',
          message: err.message,
          type: 'error',
        })
        return
      }
      // 上传图片，返回结果，将图片插入到编辑器中
    }
  }
}

// 将文章内容整合上传
